package com.zdsoft.site.mina.codec;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
/**
 * 发送数据时数据编码器
 * @author cqyhm
 *
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class P2PStringEncoder extends ProtocolEncoderAdapter{
	
	private Logger logger=LoggerFactory.getLogger(getClass());
	
    private final Charset charset;

    public P2PStringEncoder(Charset charset) {
        this.charset = charset;
    }
    
    public P2PStringEncoder() {
        this(Charset.defaultCharset());
    }
    /**实际编码方法*/
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    	logger.debug("1.1.发送数据编码器执行:IoBuffer={}",message instanceof IoBuffer);
    	if(message instanceof IoBuffer){
    		logger.debug("1.2.发送原始数据报文已经是IoBuffer");
    		out.write(message);
    	}else{
    		String value = (String)message;  //发送的字符串
            out.write(IoBuffer.wrap(value.getBytes(charset)));//数据转换为IoBuffer发送	
    	}
    }
}
